package com.yxmadoc.umlproject.service.impl;

import com.yxmadoc.umlproject.model.Order;
import com.yxmadoc.umlproject.repository.OrderRepository;
import com.yxmadoc.umlproject.repository.RepairPriceRepository;
import com.yxmadoc.umlproject.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderRepository repository;
	@Autowired
	private RepairPriceRepository repairPriceRepository;

	@Override
	public Order save(Order order) {
		return repository.save(order);
	}

	@Override
	public void delete(Integer orderId) {
		if(!repository.exists(orderId)){
			throw new RuntimeException("无此工单ID！");
		}
		repository.delete(orderId);
	}

	@Override
	public Order customerRepairerSelection(Integer priceId, Integer orderId) {
		if(!repository.exists(orderId)){
			throw new RuntimeException("无此工单ID！");
		}
		if (!repairPriceRepository.exists(priceId)) {
			throw new RuntimeException("无此报价ID！");
		}
		Order order = repository.findOne(orderId);
		order.setPriceId(priceId);
		order.setQuotated(true);
		return repository.save(order);
	}

	@Override
	public Page<Order> listByCustomer(String customerId, Pageable pageable) {
		return repository.findAllByCustomerId(customerId, pageable);
	}

	@Override
	public Page<Order> listByRepairer(String  repairerId, Pageable pageable) {
		return repository.findAllByRepairerId(repairerId, pageable);
	}

	@Override
	public Order findOne(Integer orderId) {
		return repository.findOne(orderId);
	}

	@Override
	public Order completeOrder(Integer orderId) {
		if(!repository.exists(orderId)){
			throw new RuntimeException("无此工单ID！");
		}
		Order order = repository.findOne(orderId);
		order.setCompleted(true);
		return repository.save(order);
	}

	@Override
	public Page<Order> listByQuotatedFalse(Pageable pageable) {
		return repository.findAllByQuotatedFalse(pageable);
	}

	@Override
	public Page<Order> listByCommentedFalse(String customerId, Pageable pageable) {
		return repository.findAllByCustomerIdAndCommentedFalse(customerId, pageable);
	}

	@Override
	public Order comment(Order order) {
		order.setCommented(true);
		return repository.save(order);
	}
}
